<template>
    <div class="cart">
        <van-nav-bar title="购物车" fixed placeholder
                     :right-text="manage ? '完成' : '管理'" :border="false"
                     @click-right="manage = !manage">
        </van-nav-bar>
        <empty image="search" v-if="emptyItems" description="购物车竟然是空的"/>
        <div class="cart-store-items" v-for="(items, storeId) in storeItems" :key="storeId" v-else>
            <cart-items-header :store-id="storeId"/>
            <cart-item v-for="item in items" :key="item.id" :item="item"
                       @option-selections-click="handleOptionSelectionsClick"/>
            <white-space/>
        </div>
        <cart-item-selection v-model="optionSelectionVisible"
                             :item="optionSelectionCartItem"
                             @ok="handleOptionSelectionsOk"/>
        <white-space/>
        <cart-submit-bar :manage="manage"/>
        <tabbar/>
    </div>
</template>

<script>
  import Tabbar from "@/components/Tobbar"
  import { NavBar, SubmitBar, Toast } from "vant"
  import WhiteSpace from "@/components/WhiteSpace"
  import CartItem from "@/views/cart/CartItem"

  import * as _ from "lodash"
  import CartSubmitBar from "@/views/cart/CartSubmitBar"
  import { createNamespacedHelpers } from "vuex"
  import CartItemsHeader from "@/views/cart/CartItemsHeader"
  import CartItemSelection from "@/views/cart/CartItemSelection"
  import Empty from "@/components/Empty"

  const { mapActions, mapState } = createNamespacedHelpers("cart")

  export default {
    name: "Cart",
    components: {
      Empty,
      CartItemSelection,
      CartItemsHeader,
      CartSubmitBar,
      CartItem,
      WhiteSpace,
      Tabbar,
      [NavBar.name]: NavBar,
      [SubmitBar.name]: SubmitBar,
    },
    data() {
      return {
        manage: false,
        optionSelectionVisible: false,
        optionSelectionCartItem: undefined,
      }
    },
    computed: {
      ...mapState(["items"]),
      emptyItems() {
        return _.isEmpty(this.items)
      },
      storeItems() {
        return _.chain(this.items).groupBy("storeId").value()
      },
    },
    created() {
      this.refresh()
    },
    methods: {
      ...mapActions({
        refreshAction: "refresh",
      }),
      handleOptionSelectionsClick(item) {
        this.optionSelectionVisible = true
        this.optionSelectionCartItem = item
      },
      handleOptionSelectionsOk() {
        this.refresh()
      },
      refresh() {
        Toast.loading()
        this.refreshAction()
          .finally(() => Toast.clear())
      },
    },
  }
</script>

<style scoped>
    .cart-store-items {
        background: #fff;
        margin-top: 9px;
    }

    .van-tabbar__placeholder {
        height: 100px !important;
    }
</style>
